<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\BaseController;
use app\common\model\Product\Product as ProductModel;
use think\facade\View;
use app\common\model\Product\Type as TypeModel;
use app\common\model\Product\Vip as VipModel;
use app\common\validate\Product\Product as ProductValidate;
use think\exception\ValidateException;
use app\common\validate\Product\Vip as VipValidate;

class Product extends BaseController
{
    protected $middleware = [
        Auth::class
    ];

    protected function initialize()
    {
        parent::initialize();

        $this->ProductModel = new ProductModel();

        $this->VipModel = new VipModel();
    }

    public function index()
    {
        $nav_title = [
            'nav_title' => '商品管理',
            'title' => '商品列表'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','productname');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {

            if ($SearchField == 'typename') {
                $where[] = ['type.name', 'LIKE', "%$keyword%"];
            } elseif ($SearchField == 'productname') {

                $where[] = ['product.name', 'LIKE', "%$keyword%"];
            }
            
        }else{
            $keyword = '请输入相应的内容';
        }

        // 查询
        $ProductList = ProductModel::hasWhere('type')->where($where)->order('id','desc')->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($ProductList->currentPage() - 1) * $ProductList->listRows();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'ProductList' => $ProductList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    public function recycle()
    {
        $nav_title = [
            'nav_title' => '商品管理',
            'title' => '回收站'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','productname');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {

            if ($SearchField == 'typename') {
                $where[] = ['type.name', 'LIKE', "%$keyword%"];
            } elseif ($SearchField == 'productname') {

                $where[] = ['product.name', 'LIKE', "%$keyword%"];
            }
            
        }else{
            $keyword = '请输入相应的内容';
        }

        // 查询
        $ProductList = ProductModel::onlyTrashed()->hasWhere('type')->where($where)->order('id','desc')->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($ProductList->currentPage() - 1) * $ProductList->listRows();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'ProductList' => $ProductList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    public function add()
    {
        $nav_title = [
            'nav_title' => '商品管理',
            'title' => '新增商品'
        ];

        if($this->request->isPost())
        {

            $params = $this->request->param();
            

            // 商品数据
            $ProductData = [
                'typeid' => $params['typeid'],
                'name' => $params['name'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'content' => $params['content'],
                'flag' => $params['flag']
            ];


            // 上传图片
            $cover = uploads('coverArr');

            if($cover['code'] === 0)
            {
                $this->error($cover['msg']);
            }

            $ProductData['thumbs'] = json_encode($cover['data']);

            try {
                validate(ProductValidate::class)->check($ProductData);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }

            $ProductStatus = $this->ProductModel->save($ProductData);

            if($ProductStatus !== true)
            {
                $this->error('新增商品失败');
            }else {
                $this->success('新增商品成功',(String)url('admin/product/index'));
            }
            
        }

        $TypeList = TypeModel::select();

        return View::fetch('',[
            'nav_title' => $nav_title,
            'TypeList' => $TypeList
        ]);
    }


    public function edit()
    {
        $nav_title = [
            'nav_title' => '商品管理',
            'title' => '修改商品'
        ];

        $TypeList = TypeModel::select();

        $proid = $this->request->param('proid');

        $product = $this->ProductModel->with('type')->find($proid);

        $thumbs = isset($product['thumbs']) ? json_decode($product['thumbs'],true) : [];

        $product['thumbs'] = isset($product['thumbs']) ? json_decode($product['thumbs'],true) : [];

        if(!$product)
        {
            $this->error('商品不存在');
        }


        if($this->request->isPost())
        {
            $params = $this->request->param();

            // 商品数据
            $ProductData = [
                'typeid' => $params['typeid'],
                'name' => $params['name'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'content' => $params['content'],
                'flag' => $params['flag']
            ];

            if(isset($_FILES['coverArr']) && $_FILES['coverArr']['size'] > 0)
            {
                // 上传图片
                $cover = uploads('coverArr');

                if($cover['code'] === 0)
                {
                    $this->error($cover['msg']);
                }

                $ProductData['thumbs'] = json_encode($cover['data']);
            }
            
            $ProductStatus = $product->save($ProductData);

            if($ProductStatus !== true)
            {
                if(isset($_FILES['coverArr']) && $_FILES['coverArr']['size'] > 0)
                {
                    foreach($cover as $item)
                    {
                        @is_file('./' . $item) && @unlink('./' . $item);
                    }
                }
                $this->error('修改商品失败');
            }else {
                if(isset($_FILES['coverArr']) && $_FILES['coverArr']['size'] > 0)
                {
                    // $thumbs = json_decode($product['thumbs'],true);

                    // halt($product['thumbs']);

                    foreach($thumbs as $item)
                    {
                        @is_file('./' . $item) && @unlink('./' . $item);
                    }
                }
                $this->success('修改商品成功',(String)url('admin/product/index'));
            }
        }



        return View::fetch('',[
            'nav_title' => $nav_title,
            'TypeList' => $TypeList,
            'product' => $product
        ]);
    }



    public function del()
    {
        if($this->request->isAjax())
        {
            $proid = $this->request->param('proid');

            $action = $this->request->param('action');

            if(empty($proid))
            {
                $this->error('请选择要删除商品');
            }

            if(is_array($proid))
            {
                // 批量删除操作

                // 查询数据
                if($action == 'delete')
                {
                    $idArr = ProductModel::onlyTrashed()->whereIn('id',$proid)->column('id');
                }else{

                    $idArr = ProductModel::whereIn('id',$proid)->column('id');
                }

                $NotId = '';
                
                foreach ($proid as $item) {
                    if(!in_array($item,$idArr))
                    {
                        $NotId .= $item . ',';
                    }
                }
                
                if(!empty($NotId))
                {
                    $NotId = rtrim($NotId,',');
                    $this->error("商品ID：{$NotId}不存在，请重新选择");
                }

                if($action == 'delete')
                {
                    $ProductList = ProductModel::onlyTrashed()->whereIn('id',$proid)->select();
                    $result = ProductModel::destroy($proid,true);

                }else{

                    $result = ProductModel::destroy($proid);
                }


                if($result !== true)
                {
                    $this->error('批量删除失败');
                }else{

                    if($action == 'delete')
                    {

                        if($ProductList)
                        {
                            foreach($ProductList as $item)
                            {
                                $thumbs = json_decode($item['thumbs']);

                                foreach($thumbs as $val)
                                {
                                    @is_file('./' . $val) && @unlink('./' . $val);
                                }
                            }
                        }
                    }
                    
                    $this->success('批量删除成功');
                }


            }else{
                // 单条删除
                if($action == 'delete')
                {
                    $Product = ProductModel::onlyTrashed()->find($proid);

                }else{

                    $Product = ProductModel::find($proid);
                }


                if(!$Product)
                {
                    $this->error('该商品不存在，请重新选择');
                }

                if($action == 'delete')
                {
                    $result = ProductModel::destroy($proid,true);

                }else{

                    $result = ProductModel::destroy($proid);
                }

                

                if($result !== true)
                {
                    $this->error('删除失败');
                }else{
                    if($action == 'delete')
                    {
                        if($Product)
                        {
                            $thumbs = json_decode($Product['thumbs'],true);

                            foreach($thumbs as $item)
                            {
                                @is_file('./' . $item) && @unlink('./' . $item);
                            }
                        }

                    }
                    $this->success('删除成功');
                }

            }
        }
    }

    // 恢复
    public function recovery()
    {
        if($this->request->isPost())
        {
            $proid = $this->request->param('proid');

            if(empty($proid))
            {
                $this->error('请选择要恢复的记录');
            }


            if(is_array($proid))
            {

                $PostList = ProductModel::onlyTrashed()->whereIn('id',$proid)->column('id');

                $NotId = '';

                foreach($proid as $item)
                {
                    if(!in_array($item,$PostList))
                    {
                        $NotId .= $item . ',';
                    }
                }

                $NotId = rtrim($NotId,',');

                if(!empty($NotId))
                {
                    $this->error("ID：{$NotId}不存在，请重新选择");
                }

                $result = ProductModel::onlyTrashed()->whereIn('id',$proid)->update(['deletetime' => null]);

                

                if($result != true)
                {
                    $this->error('批量恢复失败');
                }else{
                    $this->success('批量恢复成功');
                }

            }else{
                $post = ProductModel::onlyTrashed()->find($proid);

                if(!$post)
                {
                    $this->error('要恢复的的记录不存在');
                }

                // 还原
                $result = $post->restore();

                if($result !== true)
                {
                    $this->error('恢复失败');
                }else{
                    $this->success('恢复成功');
                }
            }
        }
    }
}
